package cn.itcast;


import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class HttpPostParam2TestDemo {
    public static void main(String[] args) throws URISyntaxException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
        //1.将多个参数放到一个list集合内封装起来
        List<NameValuePair> params = new ArrayList<>();
        //2. 将参数封装到到集合内
        params.add(new BasicNameValuePair("keys", "Java"));
        //3. 创建表单对象 第一个参数是封装好的参数集合, 第二个参数是编码集
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
        //4. 将表单加入到post请求种
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            if (response.getCode() == 200) {
                String entity = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(entity);
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

}
